<?php
/**
 * peck 文件助手
 *
 * @filesource _file.class.class.php
 * @package peck
 * @subpackage _helper
 * @version $id: 0.1, utf8, Tue Jan 26 20:40:03 CST 2010
 * @author LD King <kldscs[at]gmail.com>
 * @copyright Copyleft (D.) 2007 - 2010 MiFunny China Inc.
 * @link http://mifunny.info/
 * @see  
 */
class _file{
	
	/**
	 * 检查一个路径, 返回该绝对路径
	 *   如果该路径为目录, 则创建目录;
	 *   如果是一个文件, 创建它的上层目录;
	 * 
	 * @param string $path
	 * @param string $dirname
	 * @param blooean $is_file
	 * 
	 * @return string
	 */
	public static function check($path, $dirname=null, $is_file=false){
	 	if(empty($dirname)){
	 		$real_dir = '';
	 	}else{
	 		$real_dir = rtrim($dirname, '\\/');
	 	}

        if( !empty($path) ) {
            $tt = $real_dir.DIRECTORY_SEPARATOR.$path;
            if( is_dir($tt) ){ //存在目录,直接返回
                return $tt;
            }

	 		$d = preg_split('/\/|\\\/', $path, -1, PREG_SPLIT_NO_EMPTY);
            $d = array_diff($d, array('.',) );
            $count = count($d);
            if($count > 0){
                for($i=0; $i<$count-1; $i++){
	 			    $real_dir .= DIRECTORY_SEPARATOR.$d[$i];
	 		  	    if( !is_dir($real_dir) ){
                   	    mkdir($real_dir, 0700);
                    }
	 		    }
	 		    $real_dir .= DIRECTORY_SEPARATOR.$d[$count-1];
	 		    if($is_file==false){
	 			    mkdir($real_dir, 0700);
                }
            }
	 		return $real_dir;
	 	}else{
	 		throw new LogicException('('.__METHOD__.')Error: empty path !');
	 		return false;
	 	}
	}//END func check
	 		
	/**
	 * 删除文件/文件夹
	 * 
	 * @param string $path 文件路径
	 * @param blooean $is_root 是否删除根目录
	 *    例: rm('/tmp/abc', true); 清空abc文件夹
	 *        rm('/tmp/abc/', false); 递归删除abc
	 */
	public static function rm($path, $is_root=false){
		if(is_dir($path)){
			if($is_root) $cycles = true;
			elseif( !@rmdir($path) ) $cycles = true;
			else $cycles = false;
			
			if ( $cycles ) {
				if ( $dp = opendir($path) ) {  
                    while( ($file=readdir($dp)) != false ) {

                        if($file!='.' and $file!='..'){
                            $file = $path.DIRECTORY_SEPARATOR.$file;
                            if ( is_dir($file) ) {
                                $this->delete( $file );
                             } else {
					            unlink( $file );
                             }
                        }//. ..
					}
                    closedir($dp);
                    if( !$is_root ) rmdir($path); 
				}else{
					throw new RuntimeException("Can't open directory: {$path}");
				}
			}//all ready remove dir
		}else unlink($path);
	}
	
}//END class _file
?>
